package com.atguigu.gmall.common.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.model.GmallCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     *  发送消息
     * @param exchange 交换机
     * @param routingKey 路由键
     * @param message 消息
     */
    public boolean sendMessage(String exchange, String routingKey, Object message) {
        GmallCorrelationData gmallCorrelationData = new GmallCorrelationData();
        String uuid = UUID.randomUUID().toString().replace("-","");
        gmallCorrelationData.setId(uuid);
        gmallCorrelationData.setMessage(message);
        gmallCorrelationData.setExchange(exchange);
        gmallCorrelationData.setRoutingKey(routingKey);
        rabbitTemplate.convertAndSend(exchange, routingKey, message,gmallCorrelationData);
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(gmallCorrelationData),10, TimeUnit.MINUTES);

        return true;
    }

    public boolean sendDelayMsg(String exchange, String routingKey, Object msg, int delayTime) {
        GmallCorrelationData gmallCorrelationData = new GmallCorrelationData();
        String uuid = UUID.randomUUID().toString().replace("-","");
        gmallCorrelationData.setId(uuid);
        gmallCorrelationData.setMessage(msg);
        gmallCorrelationData.setExchange(exchange);
        gmallCorrelationData.setDelay(true);
        gmallCorrelationData.setRoutingKey(routingKey);
        gmallCorrelationData.setDelayTime(delayTime);
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(gmallCorrelationData),10, TimeUnit.MINUTES);
        rabbitTemplate.convertAndSend(exchange,routingKey,msg,
                message -> {
                    message.getMessageProperties().setDelay(1000*delayTime);
                    return message;
                },gmallCorrelationData);
        return true;
    }
}
